package org.wotou.authority.system.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.wotou.authority.domain.wtlogDO;
import org.wotou.authority.service.HtlogService;
import org.wotou.authority.utils.Constant;
import org.wotou.authority.utils.IpUtil;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

//import javax.servlet.http.HttpSession;

/**
 * 日志切面
 *
 * @author zhangQ
 * @date 2017/11/23
 */
@Aspect
@Component
public class LoggerAspect {

    //本地异常日志记录对象
    private static final Logger logger = LoggerFactory.getLogger(LoggerAspect.class);

    @Autowired
    private HtlogService htlogService;

    /**
     * Controller层切点
     */
    @Pointcut("@annotation(org.wotou.authority.system.aspect.SystemControllerLog)")
    public void controllerAspect() {
    }

    /**
     * 前置通知 用于拦截Controller层记录用户的操作
     *
     * @param joinPoint
     */
    @Before("controllerAspect()") //该标签声明次方法是一个前置通知：在目标方法开始之前执行
    public void beforMethod(JoinPoint joinPoint) {
        // 获取request
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
//        HttpSession session = request.getSession();
        // 读取session中的用户
//        htadminDO htadmin = (htadminDO) session.getAttribute(Constant.USER_SESSION_ID);

        //请求的IP
        String ip = IpUtil.getIp2(request);
        try {
            /* 控制台输出 */
            System.out.println("=====前置通知开始=====");
            System.out.println("请求方法:" + (joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName() + "()"));
            System.out.println("方法描述:" + getControllerMethodDescription(joinPoint));
//            System.out.println("请求人:" + htadmin.getUserName());
            System.out.println("请求IP:" + ip);
            System.out.println("=====前置通知结束=====");
            /* 数据库操作日志 */
            wtlogDO htlog = new wtlogDO();
            htlog.setUserName("用户名");
            htlog.setLoginIp(ip);
            htlog.setResultTf(Constant.RESULTIF_RIGHT);
            htlog.setCreateTime(new Date());
            htlog.setLoginOs(System.getProperty("os.name"));
            htlog.setDescription(getControllerMethodDescription(joinPoint));
            htlog.setLogLevel(wtlogDO.LOG_LEVEL_OPERA);
            htlogService.saveHtlog(htlog);
            /* 保存数据库 */
        } catch (Exception e) {
            //记录本地异常日志
            logger.error("==前置通知异常==");
            logger.error("异常信息:{}", e.getMessage());
        }
     /*   logger.error("异常方法:{},请求人:{},请求时间:{},IP:{}",
                joinPoint.getTarget().getClass().getName() + joinPoint.getSignature().getName(), htadmin.getUserName(), new Date(), ip);*/

    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param joinPoint 切点
     * @return 方法描述
     * @throws Exception
     */
    public static String getControllerMethodDescription(JoinPoint joinPoint) throws Exception {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        Object[] arguments = joinPoint.getArgs();
        Class targetClass = Class.forName(targetName);
        Method[] methods = targetClass.getMethods();
        String description = "";
        for (Method method : methods) {
            if (method.getName().equals(methodName)) {
                Class[] clazzs = method.getParameterTypes();
                if (clazzs.length == arguments.length) {
                    description = method.getAnnotation(SystemControllerLog.class).description();
                    break;
                }
            }
        }
        return description;
    }
}
